/*
 * @Author: 凌宇king
 * @Date: 2022-09-24 08:35:47
 * @LastEditTime: 2022-09-27 09:18:07
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/Home'),
    children: [
      //其他需要在Home页面显示的子页面 
      {
        path: '/admin',
        name: 'admin',
        component: () => import('@/views/Home/Admin'),
        meta: { role: '超级管理员' }
      },
      {
        path: '/home',
        redirect: '/order',
      },
      {
        path: '/order',
        name: 'order',
        component: () => import('@/views/Home/Order')
      },
      {
        path: '/total',
        name: 'total',
        component: () => import('@/views/Home/Total')
      },
      {
        path: '/adminEdit',
        name: 'adminEdit',
        component: () => import('@/views/Home/AdminEdit')
      },
      {
        path: '/orderview',
        name: 'orderview',
        component: () => import('@/views/Home/OrderView')
      }
    ]
  },
  {
    path: '*',
    redirect: '/home'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//前置路由守卫，判断路由权限
router.beforeEach((to, from, next) => {
  const { role } = to.meta;
  if (role) {
    if (!localStorage.getItem('admin')) {
      alert('请重新登录!')
      location.href = 'http://localhost:8000/login'
      return
    }
    const admin = JSON.parse(localStorage.getItem('admin'))
    if (role != admin.role) { alert('您无权访问！'); } else { next() }
  }
  else {
    next();
  }
})

export default router
